package channelService

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-channel-common/channelLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisRpc"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Hex"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"go-fox-edge-channel-udp-client/socketServer"
	"strconv"
)

type executeService struct {
}

func (e *executeService) execute(requestVO *commRedisRpc.ChannelRequestVO) (*commRedisRpc.ChannelRespondVO, error) {
	if requestVO.Send == nil {
		return nil, errors.New("发送数据不能为空！")
	}
	if requestVO.Timeout == 0 {
		return nil, errors.New("超时参数不能为空！")
	}

	param := requestVO.Send.(map[string]interface{})
	host := Map.GetString(param, "host", "")
	port := Map.GetInt(param, "port", 0)
	data := Map.GetString(param, "data", "")

	if host == "" || port == 0 || data == "" {
		return nil, errors.New("参数缺失：host, port, data")
	}

	// 格式转换
	send := Hex.DecodeString(data)

	addr := host + ":" + strconv.Itoa(port)

	// 发送数据
	socketServer.Send(addr, send)

	// 打印日志
	channelLogger.PrintChannelDebugLogger(requestVO.Name, "发送", data)

	// 等待数据返回
	val := socketServer.Event.Wait(addr, int64(requestVO.Timeout))
	if val == nil {
		return nil, errors.New("接收socket数据返回失败:设备响应超时！")
	}
	pack := val.(*socketServer.Pack)

	buffer := pack.Data
	recv := Hex.EncodeToString(buffer)

	// 打印日志
	channelLogger.PrintChannelDebugLogger(requestVO.Name, "接收", recv)

	respondVO := commRedisRpc.Type.ChannelRespondVO.Ok(requestVO)
	respondVO.Recv = recv
	return respondVO, nil
}
